package com.hrsoft.edi.qimen;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import com.hrsoft.edi.qimen.listener.EntryOrderConfirmListenner;
import com.hrsoft.edi.qimen.listener.InventoryReportListenner;
import com.hrsoft.edi.util.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.bind.annotation.*;

import com.hrsoft.edi.stub.consant.AppInfo;
import com.hrsoft.edi.util.QimenUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("qimen")
@DependsOn("beanUtils")
public class QimenController
{
    private final Map<String, QimenListenner> receiveListeners = new HashMap<>();

    @PostConstruct
    public void init()
    {
        receiveListeners.put("entryorder.confirm", BeanUtils.getBean(EntryOrderConfirmListenner.class));
        receiveListeners.put("inventory.report", BeanUtils.getBean(InventoryReportListenner.class));
    }
    
    @RequestMapping(value = "/service", method = RequestMethod.POST)
    @ResponseBody
    public String router(HttpServletRequest request, @RequestBody String data)
    {
        String response = null;
        try
        {
            String requestUrl = request.getRequestURI() + "?" + request.getQueryString();
            
            Map<String, String> params = QimenUtils.getParamsFromUrl(requestUrl);
            
            String method = params.get("method");
            String sign = params.get("sign");
            String appKey = params.get("app_key");
            String customerCode = params.get("customerId");

            // appkey等的校验 如果自己是多租户系统 可以根据appkey去获取相关的配置信息

            // TODO 根据APPKEY去查配置的secret 如果是支持多个appkey的情况
            String secret = AppInfo.SECRET;
            
            String xml = null;
            
            if (data.indexOf("<") > 0)
            {
                xml = data.substring(data.indexOf("<"));
            }
            else
            {
                xml = data;
            }
            
            // 过滤emoji字符
            xml = filterEmoji(xml, "");
            
            log.info("接收到的请求为:" + requestUrl);
            log.info("接收到的报文为:" + xml);
            
            String mySign = QimenUtils.sign(params, xml, secret);
            
//            if (!sign.equals(mySign))
//            {
//                response = QimenUtils.getCommonResponse("400", "failure", "Sign verify failed");
//            }
//            else
//            {
                QimenListenner processsor = receiveListeners.get(method);
                if (null == processsor)
                {
//                    response = QimenUtils.getCommonResponse("200", "failure", "没有找到对应的监听处理器");
                    response = QimenUtils.getCommonResponse("200", "success", "没有找到对应的监听处理器");

                }
                else
                {
                    response = processsor.doBiz(xml, null);
                }
//            }
        }
        // TODO 捕获业务异常
        // catch (BusinessException e)
        // {
        // response = QimenUtils.getCommonResponse("200", "failure", e.getMessage());
        // }
        // 捕获未知异常
        catch (Exception e)
        {
            log.error("奇门接口处理失败", e);
            response = QimenUtils.getCommonResponse("500", "failure", "系统内部错误");
        }
        
        return response;
    }
    
    public static String filterEmoji(String source, String slipStr)
    {
        if (StringUtils.isNotBlank(source))
        {
            return source.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", slipStr);
        }
        else
        {
            return source;
        }
    }
    
}
